<template>
  <!-- 确认对话框 -->
  <a-modal
    v-model:visible="confirmVisible"
    :title="confirmData.title"
    @ok="handleConfirmOk"
    @cancel="handleConfirmCancel"
    :ok-button-props="{ 
      status: confirmData.danger ? 'danger' : 'normal',
      loading: confirmLoading
    }"
    :ok-text="confirmData.okText || '确认'"
    :cancel-text="confirmData.cancelText || '取消'"
    :unmount-on-close="true"
    :footer-before="hasReason ? 'reason' : undefined"
  >
    <div class="confirm-content">
      <a-space>
        <a-avatar :style="{ backgroundColor: confirmData.iconColor || '#165DFF' }">
          <component :is="dynamicIconComponent" />
        </a-avatar>
        <div class="confirm-message">
          <p>{{ confirmData.content }}</p>
          <p v-if="confirmData.warning" class="confirm-warning">
            <icon-exclamation-circle-fill /> {{ confirmData.warning }}
          </p>
        </div>
      </a-space>
    </div>
    
    <template #reason>
      <div class="confirm-reason">
        <a-form-item 
          field="reason" 
          label="操作原因" 
          :rules="[{ required: true, message: '请输入操作原因' }]"
          :validate-trigger="['change', 'blur']"
        >
          <a-textarea 
            v-model="confirmData.reason" 
            placeholder="请输入操作原因" 
            allow-clear 
          />
        </a-form-item>
      </div>
    </template>
  </a-modal>
  
  <!-- 结果通知 -->
  <a-modal
    v-model:visible="resultVisible"
    :title="resultData.title"
    :footer="false"
    :unmount-on-close="true"
    :mask-closable="true"
  >
    <div class="result-content">
      <div class="result-icon">
        <a-icon 
          v-if="resultData.status === 'success'" 
          :size="64" 
          style="color: #00B42A" 
        >
          <icon-check-circle-fill />
        </a-icon>
        <a-icon 
          v-else-if="resultData.status === 'error'" 
          :size="64" 
          style="color: #F53F3F"
        >
          <icon-close-circle-fill />
        </a-icon>
        <a-icon 
          v-else-if="resultData.status === 'warning'" 
          :size="64" 
          style="color: #FF7D00"
        >
          <icon-exclamation-circle-fill />
        </a-icon>
        <a-icon 
          v-else 
          :size="64" 
          style="color: #165DFF"
        >
          <icon-info-circle-fill />
        </a-icon>
      </div>
      
      <div class="result-message">
        <h3>{{ resultData.message }}</h3>
        <p v-if="resultData.description">{{ resultData.description }}</p>
      </div>
      
      <div class="result-detail" v-if="hasResultDetail">
        <a-divider style="margin: 16px 0" />
        
        <a-descriptions 
          :column="1" 
          title="详细信息" 
          layout="vertical"
          size="small"
        >
          <a-descriptions-item 
            v-for="(item, index) in resultData.details" 
            :key="index" 
            :label="item.label"
          >
            <template v-if="item.type === 'tag'">
              <a-tag :color="item.color">{{ item.value }}</a-tag>
            </template>
            <template v-else-if="item.type === 'status'">
              <a-badge :status="item.status" :text="item.value" />
            </template>
            <template v-else>
              {{ item.value }}
            </template>
          </a-descriptions-item>
        </a-descriptions>
        
        <div v-if="resultData.items && resultData.items.length > 0" class="result-items">
          <div class="result-items-header">
            <div v-for="(header, index) in resultData.headers" :key="index" class="result-item-header">
              {{ header }}
            </div>
          </div>
          <div v-for="(item, index) in resultData.items" :key="index" class="result-item">
            <div v-for="(value, key, idx) in item" :key="key" class="result-item-cell">
              <template v-if="typeof value === 'object' && value !== null">
                <a-tag v-if="value.type === 'tag'" :color="value.color">{{ value.text }}</a-tag>
                <span v-else>{{ JSON.stringify(value) }}</span>
              </template>
              <template v-else>
                {{ value }}
              </template>
            </div>
          </div>
        </div>
      </div>
      
      <div class="result-actions">
        <a-space>
          <a-button 
            v-if="resultData.primaryAction" 
            type="primary" 
            @click="handlePrimaryAction"
          >
            {{ resultData.primaryAction.text }}
          </a-button>
          <a-button 
            v-if="resultData.secondaryAction" 
            @click="handleSecondaryAction"
          >
            {{ resultData.secondaryAction.text }}
          </a-button>
          <a-button v-else @click="closeResult">
            关闭
          </a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, computed, defineExpose, h } from 'vue';
import { Message, Notification, Progress as AProgress } from '@arco-design/web-vue';
import {
  IconInfo,
  IconExclamationCircle,
  IconCheckCircleFill,
  IconCloseCircleFill,
  IconExclamationCircleFill,
  IconInfoCircleFill,
  IconLoading,
  IconLeft,
  IconRight,
  IconDelete,
  IconCheck,
  IconClose,
} from '@arco-design/web-vue/es/icon';

// Define a map for string-to-component conversion
const iconMap = {
  'icon-info': IconInfoCircleFill,
  'icon-exclamation-circle': IconExclamationCircleFill,
  'icon-check-circle': IconCheckCircleFill,
  'icon-close-circle': IconCloseCircleFill,
  'icon-warning': IconExclamationCircleFill,
  'icon-delete': IconDelete,
  'icon-check': IconCheck,
  'icon-close': IconClose,
  'icon-loading': IconLoading,
};

// 确认对话框数据
const confirmVisible = ref(false);
const confirmLoading = ref(false);
const confirmData = ref({
  title: '确认操作',
  content: '确定要执行此操作吗？',
  okText: '确认',
  cancelText: '取消',
  danger: false,
  warning: '',
  icon: 'icon-info',
  iconColor: '#165DFF',
  reason: '',
  needReason: false,
  resolve: null,
  reject: null
});

// Computed property to get the actual icon component
const dynamicIconComponent = computed(() => {
  return iconMap[confirmData.value.icon] || IconInfoCircleFill;
});

// 结果通知数据
const resultVisible = ref(false);
const resultData = ref({
  title: '操作结果',
  status: 'success',
  message: '操作成功',
  description: '',
  details: [],
  headers: [],
  items: [],
  primaryAction: null,
  secondaryAction: null
});

// 进度指示器数据
const progressVisible = ref(false);
const progressData = ref({
  key: 'default',
  title: '处理中...',
  total: 1,
  current: 0,
  percent: 0,
  status: 'normal',
  message: '',
  resolve: null
});

// Helper function to create promises
const createPromise = () => {
  let resolveFn, rejectFn;
  const promise = new Promise((resolve, reject) => {
    resolveFn = resolve;
    rejectFn = reject;
  });
  return { promise, resolve: resolveFn, reject: rejectFn };
};

// 显示确认对话框
const showConfirm = (options = {}) => {
  const { promise, resolve, reject } = createPromise();
  confirmData.value = {
    ...confirmData.value,
    ...options,
    reason: '',
    resolve,
    reject
  };
  confirmLoading.value = false;
  confirmVisible.value = true;
  return promise;
};

// 确认对话框 - 确定
const handleConfirmOk = async () => {
  if (hasReason.value && !confirmData.value.reason) {
    Message.warning('请输入操作原因');
    return;
  }
  
  confirmLoading.value = true;
  try {
    if (confirmData.value.onOk && typeof confirmData.value.onOk === 'function') {
      await confirmData.value.onOk(confirmData.value.reason);
    }
    confirmData.value.resolve(confirmData.value.reason || true);
    confirmVisible.value = false;
  } catch (error) {
    console.error('Confirm OK callback error:', error);
    confirmData.value.reject(error);
    confirmVisible.value = false;
  } finally {
    confirmLoading.value = false;
  }
};

// 确认对话框 - 取消
const handleConfirmCancel = () => {
  confirmData.value.reject(false);
  confirmVisible.value = false;
};

// 是否需要显示原因输入框
const hasReason = computed(() => confirmData.value.needReason);

// 显示结果通知
const showResult = (options = {}) => {
  resultData.value = {
    ...resultData.value,
    ...options
  };
  resultVisible.value = true;
};

// 关闭结果通知
const closeResult = () => {
  resultVisible.value = false;
};

// 结果通知 - 主操作
const handlePrimaryAction = () => {
  if (resultData.value.primaryAction?.callback) {
    resultData.value.primaryAction.callback();
  }
  closeResult();
};

// 结果通知 - 次操作
const handleSecondaryAction = () => {
  if (resultData.value.secondaryAction?.callback) {
    resultData.value.secondaryAction.callback();
  }
  closeResult();
};

// 是否有详细信息
const hasResultDetail = computed(() => {
  return (resultData.value.details && resultData.value.details.length > 0) || 
         (resultData.value.items && resultData.value.items.length > 0);
});

// 显示进度条
const showProgress = (options = {}) => {
  const { promise, resolve } = createPromise();
  progressData.value = {
    ...progressData.value,
    ...options,
    current: 0,
    percent: 0,
    status: 'normal',
    message: '准备中...',
    resolve
  };
  
  const key = `progress-${progressData.value.key}-${Date.now()}`;
  
  // Function to generate VNode content using h()
  const renderContent = (percent, status, message) => {
    return h('div', [
      h(AProgress, { // Use imported AProgress component
        percent: Math.min(100, percent), // 确保百分比不超过100
        status: status,
        size: 'large'
      }),
      h('p', { style: 'margin-top: 8px;' }, message)
    ]);
  };
  
  // Store the close function returned by Notification
  let closeNotification = null;
  
  // Function to display or update notification
  const displayNotification = (config) => {
    console.log('[Feedback] Attempting to display/update notification. Current closeNotification:', typeof closeNotification, closeNotification);
    
    // Close previous notification only if it exists and is a function
    if (typeof closeNotification === 'function') {
      try {
        closeNotification();
        console.log('[Feedback] Previous notification closed successfully.');
        closeNotification = null; // Reset after closing
      } catch (e) {
        console.error('[Feedback] Error closing previous notification:', e);
        // Even if closing failed, reset the handle to prevent further errors
        closeNotification = null; 
      }
    } else if (closeNotification) {
      console.warn('[Feedback] closeNotification exists but is not a function:', closeNotification);
      closeNotification = null; // Reset invalid handle
    }

    // Display new notification and store its close function
    try {
      const returnedValue = Notification.info(config);
      console.log('[Feedback] Notification.info was called. Returned value:', typeof returnedValue, returnedValue);
      
      if (returnedValue && typeof returnedValue.close === 'function') {
        closeNotification = returnedValue.close;
        console.log('[Feedback] Stored close function successfully.');
      } else {
        console.warn('[Feedback] Notification.info did not return an object with a close function. Cannot close this notification programmatically.', returnedValue);
        closeNotification = null; // Ensure it's null if not found
      }
    } catch (e) {
       console.error('[Feedback] Error displaying notification via Notification.info:', e);
       closeNotification = null; // Reset on error
    }
  };

  // Initial display
  displayNotification({
    id: key, // Use the same ID for potential manual closing if needed, though we rely on the returned function
    title: progressData.value.title,
    content: () => renderContent(
      Math.min(100, progressData.value.percent), // 确保百分比不超过100
      progressData.value.status,
      progressData.value.message
    ),
    duration: 0, // Keep open until closed programmatically
    closable: false
  });
  
  return {
    update: (current, message = '') => {
      progressData.value.current = current;
      
      // 确保百分比计算正确且不超过100
      const calculatedPercent = progressData.value.total > 0 
        ? Math.round((current / progressData.value.total) * 100)
        : 0;
      progressData.value.percent = Math.min(100, calculatedPercent);
      
      progressData.value.message = message || `正在处理 ${current} / ${progressData.value.total}`;
      
      // Update notification
      displayNotification({
        id: key,
        title: progressData.value.title, // Keep the same title usually
        content: () => renderContent(
          Math.min(100, progressData.value.percent), // 确保百分比不超过100
          progressData.value.status,
          progressData.value.message
        ),
        duration: 0,
        closable: false
      });
    },
    complete: (message = '处理完成', status = 'success') => {
      // Close the last info notification if the handle is valid
      if (typeof closeNotification === 'function') {
         try {
           closeNotification();
           console.log('[Feedback] Closed final info notification before showing completion.');
         } catch (e) {
            console.error('[Feedback] Error closing final info notification:', e);
         }
      } else if (closeNotification) {
         console.warn('[Feedback] Final closeNotification handle was not a function:', closeNotification);
      }
      closeNotification = null; // Ensure handle is cleared
      
      // 确保百分比是100%，不是10000%
      progressData.value.percent = 100;
      progressData.value.status = status;
      progressData.value.message = message;
      
      // Show final status notification
      const finalNotificationMethod = status === 'success' 
        ? Notification.success 
        : (status === 'warning' ? Notification.warning : Notification.error);
        
      // 确保传入渲染函数的百分比也是100
      finalNotificationMethod({
        title: status === 'success' ? '处理成功' : (status === 'warning' ? '部分完成' : '处理失败'),
        content: () => renderContent(
          100, // 硬编码为100，确保不会超过100
          progressData.value.status,
          progressData.value.message
        ),
        duration: 3000 // Auto close after completion
      });
      progressData.value.resolve(true);
    },
    error: (message = '处理失败') => {
       // Close the last info notification if the handle is valid
      if (typeof closeNotification === 'function') {
         try {
           closeNotification();
           console.log('[Feedback] Closed final info notification before showing error.');
         } catch (e) {
            console.error('[Feedback] Error closing final info notification:', e);
         }
      } else if (closeNotification) {
         console.warn('[Feedback] Final closeNotification handle was not a function:', closeNotification);
      }
      closeNotification = null; // Ensure handle is cleared
      
      progressData.value.status = 'danger';
      progressData.value.message = message;
      
      // Show error notification
      Notification.error({
        title: '处理失败',
        content: () => renderContent(
          progressData.value.percent,
          progressData.value.status,
          progressData.value.message
        ),
        duration: 5000 // Keep open longer for errors
      });
      progressData.value.resolve(false);
    }
  };
};

// Expose methods to parent component
defineExpose({
  showConfirm,
  showResult,
  showProgress
});
</script>

<style scoped>
.confirm-content {
  padding: 12px 0;
}

.confirm-message {
  flex: 1;
}

.confirm-warning {
  color: #ff4d4f;
  margin-top: 8px;
}

.confirm-reason {
  margin-top: 16px;
}

.result-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 0;
}

.result-icon {
  margin-bottom: 24px;
}

.result-message {
  text-align: center;
  margin-bottom: 24px;
}

.result-message h3 {
  margin-bottom: 8px;
}

.result-detail {
  width: 100%;
  margin-bottom: 24px;
}

.result-items {
  margin-top: 16px;
  border: 1px solid #f2f3f5;
  border-radius: 4px;
}

.result-items-header {
  display: flex;
  background-color: #f2f3f5;
  font-weight: bold;
}

.result-item-header {
  padding: 8px 12px;
  flex: 1;
}

.result-item {
  display: flex;
  border-bottom: 1px solid #f2f3f5;
}

.result-item:last-child {
  border-bottom: none;
}

.result-item-cell {
  padding: 8px 12px;
  flex: 1;
}

.result-actions {
  margin-top: 24px;
}
</style> 